
//
// 110109 - AH - (Hector) Created.
// 110111a- AH - Missing java doc added.
// 110111b- AH - Made a RetrievalPerformedEventListener so know when to send
//               change events to view.
// 110130 - AH - (Bien) Removed old debug printout to err.
//

package org.soekrat.gui.swing.retrieval;

import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;

import org.soekrat.engine.event.RetrievalPerformedEvent;
import org.soekrat.engine.event.RetrievalPerformedEventListener;
import org.soekrat.engine.wheel.retrieval.RetrievalEvent;
import org.soekrat.engine.wheel.retrieval.RetrievalEventTree;
import org.soekrat.gui.swing.util.AbstractTreeModel;

/**
 * <p>
 *   Adapt
 *   {@link RetrievalEventTree} to a
 *   {@link JTree} view.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC) 
 */
public final class RetrievalEventTreeModel extends AbstractTreeModel
  implements RetrievalPerformedEventListener
{
  private final RetrievalEventTree m_tree;
  
  private final Object[] m_rootPath;
  
  /**
   * <p>
   *   Creates the empty model.
   * </p>
   */
  public RetrievalEventTreeModel(){ m_tree=null; m_rootPath=new Object[0]; }
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param tree {@link RetrievalEventTree} to adapt.
   */
  public RetrievalEventTreeModel(RetrievalEventTree tree)
  {
    if (tree==null)
    {
      throw new NullPointerException("tree");
    }
    
    m_tree=tree;
    m_rootPath=new Object[]{ m_tree };
  }

  // Specified in TreeModel.
  public Object getChild(Object parent, int idx)
  {
    if (parent==m_tree)
    {
      return m_tree.get(idx);
    }
    
    return ((RetrievalEvent)parent).getNext();
  }

  // Specified in TreeModel.
  public int getChildCount(Object parent) 
  {
    if (parent==m_tree)
    {
      return m_tree.size();
    }
    
    RetrievalEvent next=((RetrievalEvent)parent).getNext();
    return next==null ? 0 : 1;
  }

  // Specified in TreeModel.
  public int getIndexOfChild(Object parent, Object child) 
  {
    if (parent==m_tree)
    {
      return m_tree.indexOf((RetrievalEvent)child);
    }
    
    RetrievalEvent next=((RetrievalEvent)parent).getNext();
    return next==null ? -1 : 1;
  }

  // Specified in TreeModel.
  public Object getRoot(){ return m_tree; } 

  // Specified in TreeModel.
  public boolean isLeaf(Object node)
  {
    if (node==m_tree) return m_tree.size()==0;
    
    RetrievalEvent next=((RetrievalEvent)node).getNext();
    return next==null;
  }

  // Specified in RetrievalPerformedEventListener.
  public void retrievalPerformed(RetrievalPerformedEvent e) 
  {
    fire(new TreeModelEvent(this, m_rootPath), EventType.STRUCTURE);
    m_gtree.changed();
  }
  
  private RetrievalEventTreePanel m_gtree=null;
  
  void setGTree(RetrievalEventTreePanel t){ m_gtree=t; }
  
}
